package com.unbank.util;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.unbank.callitnew.CallitNewConsole;
import com.unbank.callitnew.entity.WebBean;

public class ConfigUtil {
	private static Document doc;

	static {
		try {
			try {
				File file = new File(CallitNewConsole.class.getClassLoader()
						.getResource("").toURI().getPath()
						+ "callitnew_config.xml");
				doc = Jsoup.parse(file, "utf-8");
			} catch (URISyntaxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// webUrl nextPage frontType detailType frontXpath detailXpath attr name
	// value
	public static List<WebBean> getWebBeans() {
		List<WebBean> beans = new ArrayList<WebBean>();
		Elements bs = doc.select("webBean");
		for (Element e : bs) {
			String url = e.select("webUrl").text().trim();
			String nextPage = e.select("nextPage").text().trim();
			String frontXpath = e.select("frontXpath").text().trim();
			String detailXpath = e.select("detailXpath").text().trim();
			String pageCount = e.select("pageCount").text().trim();
			Map<String, String> attr = new HashMap<String, String>();
			Elements attrs = e.select("attr");
			if (attrs.size() != 0 && attrs.text().length() > 5) {
				for (int i = 0; i < attrs.size(); i++) {
					attr.put(attrs.get(i).select("name").text().trim(), attrs
							.get(i).select("value").text().trim());
				}
			}
			WebBean b = new WebBean(url, nextPage, frontXpath, detailXpath,
					Integer.parseInt(pageCount), attr);
			beans.add(b);
		}
		return beans;
	}

	public static Document getDom() {
		return doc;
	}

}
